import process from 'node:process'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { z } from 'zod'
import * as dotenv from 'dotenv'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
dotenv.config({
  path: path.join(__dirname, '.env'),
})

const envSchema = z.object({
  V1_HOST: z.string().min(1),
  V1_HTTP_PORT: z.number(),
  V1_WS_PORT: z.number(),
  V1_FE_PORT: z.number(),
  // OPENAI_API_KEY: z.string().min(1),
  AZURE_OPENAI_API_ENDPOINT: z.string().min(1),
  AZURE_OPENAI_API_KEY: z.string().min(1),
  AZURE_OPENAI_API_DEPLOYMENT_NAME: z.string().min(1),
  // local clash proxy for openai
  OPENAI_PROXY: z.string().optional(),
  ANTHROPIC_API_KEY: z.string().optional(),
})
export type Env = z.infer<typeof envSchema>
const parsed = envSchema.safeParse({
  V1_HOST: process.env.V1_HOST || 'localhost',
  V1_HTTP_PORT: Number(process.env.V1_HTTP_PORT) || 3000,
  V1_WS_PORT: Number(process.env.V1_WS_PORT) || 3001,
  V1_FE_PORT: Number(process.env.V1_FE_PORT) || 8080,
  AZURE_OPENAI_API_ENDPOINT: process.env.AZURE_OPENAI_API_ENDPOINT,
  AZURE_OPENAI_API_KEY: process.env.AZURE_OPENAI_API_KEY,
  AZURE_OPENAI_API_DEPLOYMENT_NAME: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME,
  OPENAI_PROXY: process.env.OPENAI_PROXY,
  ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
})

if (parsed.success === false) {
  console.error(
    '❌ Invalid environment variables:',
    parsed.error.flatten().fieldErrors,
  )
  throw new Error('Invalid environment variables')
}

export const env = parsed.data
